package mysql

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"golang-sgg-daijia/internal/model"
	"gorm.io/gorm"
)

type OrderBillDao interface {
	Create(ctx context.Context, orderBill *model.OrderBill) error
	FindByID(ctx context.Context, id int64) (*model.OrderBill, error)
	FindByOrderID(ctx context.Context, OrderID int64) (*model.OrderBill, error)
}

func NewOrderBillDao(
	r *MysqlClient,
) OrderBillDao {
	return &orderBillDao{
		MysqlClient: r,
	}
}

type orderBillDao struct {
	*MysqlClient
}

func (r *orderBillDao) Create(ctx context.Context, orderBill *model.OrderBill) error {
	if err := r.DB(ctx).Create(orderBill).Error; err != nil {
		r.logger.WithContext(ctx).Error("orderBillDao|Create", zap.Error(err))
		return err
	}
	return nil
}

func (r *orderBillDao) FindByID(ctx context.Context, id int64) (*model.OrderBill, error) {
	orderBill := &model.OrderBill{}
	if err := r.DB(ctx).Where("id = ?", id).First(orderBill).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("orderBillDao|GetByID", zap.Error(err))
		return nil, err
	}
	return orderBill, nil
}

func (r *orderBillDao) FindByOrderID(ctx context.Context, OrderID int64) (*model.OrderBill, error) {
	orderBill := &model.OrderBill{}
	if err := r.DB(ctx).Where("order_id = ?", OrderID).First(orderBill).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("orderBillDao|FindByOrderID", zap.Error(err))
		return nil, err
	}
	return orderBill, nil
}